<template>
  <el-dialog
    v-model="isShow"
    :title="`与${userName}对话`"
    width="800"
    align-center
  >
    <div class="big-box">
      <div class="dialog-content">
      <div class="ab-box">
        <el-scrollbar height="100%">
          <talkItem v-for="(item, i) in list" :key="i" :data="item" :isMe="item.type === 1" />
        </el-scrollbar>
      </div>
      </div>
      <div class="dialog-input">
        <editorBox v-model="text" />
      </div>
    </div>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="isShow = false">取消</el-button>
        <el-button type="primary" @click="senMsg">
          发送
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script>
  import editorBox from '@/components/editorBox.vue'
  import talkItem from './talkltem.vue';
  import { sendMessageByUserId } from '@/api/talk'
  import { talkMap } from '@/socket/index'
  export default {
    components: {
      editorBox,
      talkItem
    },
    data() {
      return {
        isShow: false,
        userName: '',
        targetUserId: '',
        headImg: '',
        text: '',
        talkMap,
        list: [
          // {
          //   type: 1, // 1表示我说的 2.表示对方说的
          //   img: '', // 头像，
          //   userName: '',
          //   msg: ''
          // }
        ]
      }
    },
    computed: {
      currentTalk() {
        return this.talkMap.get(this.targetUserId) || []
      }
    },
    watch: {
      'currentTalk.length': function(val) {
        const msgStr = this.currentTalk[val - 1];
        const msgObj = this.getTargetMsgObj(msgStr)
        this.list.push(msgObj)
      }
    },
    methods: {
      open(data) {
        this.userName = data.userName
        this.targetUserId = data.userId
        this.headImg = data.headImg
        this.isShow = true
      },
      senMsg() {
        sendMessageByUserId({
          targetUserId: this.targetUserId,
          message: this.text,
          type: 2
        }).then(res => {
          const obj = this.getMyMsgObj(this.text)
          this.list.push(obj)
          this.text = ''
        })
      },
      getMyMsgObj(msg) {
        return {
          type: 1,
          userName: '我',
          msg,
          img: '/img/defalutHeader.png'
        }
      },
      getTargetMsgObj(msg) {
        return {
          type: 2,
          userName: this.userName,
          msg,
          img: this.headImg
        }
      }
    }
  }
</script>

<style lang="scss" scoped>
.big-box{
  height: 750px;
  display: flex;
  flex-direction: column;
  .dialog-content{
    flex: 1;
    position: relative;
    .ab-box{
      position: absolute;
      top: 0;
      left: 0;
      right: 0;
      bottom: 0;
    }
  }
  .dialog-input{
    height: 350px;
  }
}
</style>
